<?php

namespace App\Http\Controllers\Application;

use App\Http\Controllers\Controller;
use App\Http\Requests\Application\ColumnRecommendRequest;
use App\Models\Application\ColumnRecommend;
use App\Models\Application\ColumnRecommendData;
use App\Models\Entity\Asset\Video\Vasseti;
use App\Models\Entity\Column\Column;
use App\Models\Entity\Column\Collist;
use App\Models\Entity\Column\ColumnFun;
use App\Models\Entity\Column\Data;
use App\Models\Entity\Column\Subcolumn;
use App\Models\Entity\Tag\tag;
use App\Repositories\Application\ColumnRecommendRepository;
use Encore\Admin\Controllers\ModelForm;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Flash;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Route;
use Response;

class ColumnRecommendController extends Controller
{
    use ModelForm;

    /** @var  ColumnRecommendRepository */
    private $columnRecommendRepository;

    public function __construct(ColumnRecommendRepository $columnRecommendRepo)
    {
        $this->columnRecommendRepository = $columnRecommendRepo;
    }

    /**
     * Display a listing of the ColumnRecommend.
     *
     * @return Response
     */
    public function index()
    {
        return Admin::content(function (Content $content) {

            $content->header(__('application.column_recommends.index_header'));
            $content->description(__('application.column_recommends.index_description'));

            $content->body($this->grid());
            // $content->row(view('entity.tag.addContentTagModal'));

            $content->row(view('application.column-recommend-datas.index'));

        });
    }

    /**
     * Show the form for creating a new ColumnRecommend.
     *
     * @return Response
     */
    public function create()
    {

        return Admin::content(function (Content $content) {

            $content->header(__('application.column_recommends.create_header'));
            $content->description(__('application.column_recommends.create_description'));

            $content->body($this->form());

        });
        // $data = [];
        // // 获取数据员
        // $datas         = Data::select(['title', 'id'])->get()->toArray();
        // $tempArr = [0=>['title'=>'请选择数据源','id'=>'']];
        // $datas = array_merge($tempArr,$datas);
        // $data['datas'] = json_encode($datas);
        // Admin::script('createColumnRecommends(' . json_encode($datas) . ');');
        // // 获取栏目信息
        // $columns                    = Column::onlineStatus()->onlinePublished()->pluck('name', 'id')->toArray();
        // $data['create_header']      = __('application.column_recommends.create_header');
        // $data['create_description'] = __('application.column_recommends.create_description');
        // $data['columns']            = $columns;
        // // // 分类
        // $vcats = Vcat::get(['name', 'id']);
        // // 归类数据
        // $vcattags         = Vcattag::get(['name', 'id']);
        // $data['vcats']    = $vcats;
        // $data['vcattags'] = $vcattags;
        // return view('application.column-recommends.create', $data);
    }

    /**
     * Store a newly created ColumnRecommend in storage.
     *
     * @param ColumnRecommendRequest $request
     *
     * @return Response
     */
    public function store(ColumnRecommendRequest $request)
    {
        $input           = $request->all();
        $columnRecommend = $this->columnRecommendRepository->create($input);
        if ($columnRecommend) {
            if (is_array($request->get('columnrecommenddatas'))) {
                $columnRecommend->columnrecommenddatas()->sync(array_filter($request->get('columnrecommenddatas')));
            }
        }

        Flash::success(__('application.column_recommends.saved_success'));

        return Input::get('_previous_') ? redirect(Input::get('_previous_')) : redirect(route('application.column_recommends.index'));

    }

    /**
     * Display the specified ColumnRecommend.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function show($id)
    {
        $columnRecommend = $this->columnRecommendRepository->findWithoutFail($id);

        if (empty($columnRecommend)) {
            Flash::error(__('application.column_recommends.not_found'));

            return redirect(route('application.column_recommends.index'));
        }

        return view('application.column_recommends.show')->with('columnRecommend', $columnRecommend);

    }

    /**
     * Show the form for editing the specified ColumnRecommend.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function edit($id)
    {

        return Admin::content(function (Content $content) use ($id) {

            $content->header(__('application.column_recommends.edit_header'));
            $content->description(__('application.column_recommends.edit_description'));

            $content->body($this->form()->edit($id));
        });
    }

    /**
     * Update the specified ColumnRecommend in storage.
     *
     * @param  int              $id
     * @param ColumnRecommendRequest $request
     *
     * @return Response
     */
    public function update($id, ColumnRecommendRequest $request)
    {
        $columnRecommend = $this->columnRecommendRepository->findWithoutFail($id);

        if (empty($columnRecommend)) {
            Flash::error(__('application.column_recommends.not_found'));

            return redirect(route('application.column_recommends.index'));
        }
        $input = $request->all();

        $columnRecommend = $this->columnRecommendRepository->update($input, $id);
        if ($columnRecommend) {
            if (is_array($request->get('columnrecommenddatas'))) {
                $columnRecommend->columnrecommenddatas()->sync(array_filter($request->get('columnrecommenddatas')));
            }
        }
        Flash::success(__('application.column_recommends.updated_success'));

        return Input::get('_previous_') ? redirect(Input::get('_previous_')) : redirect(route('application.column_recommends.index'));
    }

    /**
     * Remove the specified ColumnRecommend from storage.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function destroy($id)
    {
        // 根据 `,` 判断传递过来的是单个id还是多个id
        if (substr_count($id, ',') >= 1) {
            $id = explode(",", $id);
        }

        // 如果是数组则进行批量删除
        if (is_array($id)) {
            if ($flag = $this->columnRecommendRepository->batchDelete('id', $id)) {

                return response()->json(['message' => __('application.column_recommends.deleted_success'), 'status' => $flag]);
            } else {
                return response()->json(['message' => __('base.deleted.error'), 'status' => $flag]);
            }
        }

        $columnRecommend = $this->columnRecommendRepository->findWithoutFail($id);

        if (empty($columnRecommend)) {
            Flash::error(__('application.column_recommends.not_found'));

            return redirect(route('application.column_recommends.index'));
        }

        if ($flag = $this->columnRecommendRepository->delete($id)) {

            return response()->json(['message' => __('application.column_recommends.deleted_success'), 'status' => $flag]);
        } else {
            return response()->json(['message' => __('base.deleted.error'), 'status' => $flag]);
        }
    }

    /**
     * [form description]
     * @return {[type]} [description]
     */
    protected function form()
    {
        return Admin::form(ColumnRecommend::class, function (Form $form) {

            $form->display('id', 'ID');
            $form->text('name', '名称');
            $form->text('title', '显示名称');
            $form->text('area', '区域编号');
            $form->textarea('description', '描述');
            $columns = Column::pluck('name', 'id');
            $form->select('column_id', '一级栏目')->options($columns);
            $columnRecommendDatas = ColumnRecommendData::pluck('name', 'id');
            $form->multipleSelect('columnrecommenddatas', '选择推荐数据')->options($columnRecommendDatas);
            // $form->display('created_at', __('base.created_at'));
            // $form->display('updated_at', __('base.updated_at'));

        });
    }

    /**
     * [grid description]
     * @return {[type]} [description]
     */
    protected function grid()
    {

        return Admin::grid(ColumnRecommend::class, function (Grid $grid) {
            // 考虑是否需要scope和排序
            // $grid->model()->orderBy('listorder', 'asc');

            // // 添加按钮
            // if (!\Gate::check('application.column_recommends.create')) {
            //     $grid->disableCreation();
            // }

            // // 编辑和删除按钮
            // $grid->actions(function ($actions) {
            //     // 编辑按钮
            //     if (!\Gate::check('application.column_recommends.edit')) {
            //         $actions->disableEdit();
            //     }
            //     // 删除按钮
            //     if (!\Gate::check('application.column_recommends.destroy')) {
            //         $actions->disableDelete();
            //     }
            // });

            // // 导出按钮
            // if (!\Gate::check('application.column_recommends.export')) {
            //     $grid->disableExport();
            // }

            // // 批量操作
            // $grid->tools(function ($tools) {
            //     $tools->batch(function ($batch) {
            //         // 批量删除按钮
            //         if (!\Gate::check('application.column_recommends.batch_destroy')) {
            //             $batch->disableDelete();
            //         }
            //     });
            // });

            // 添加按钮
            if (Admin::user()->cannot('application.column_recommends.create')) {
                $grid->disableCreation();
            }

            // 编辑和删除按钮
            $grid->actions(function ($actions) {
                $id = $actions->getKey();
                // 编辑按钮
                if (Admin::user()->cannot('application.column_recommends.edit')) {
                    $actions->disableEdit();
                }
                // 删除按钮
                if (Admin::user()->cannot('application.column_recommends.destroy')) {
                    $actions->disableDelete();
                }
                //推荐数据
                //打标签
                $url = route('application.column_recommends.add_recommend_data', ['column_recommend_id' => $id]);
                $actions->append('<a href="' . $url . '" data-toggle="modal"  data-target="#add-content-tag-modal" title="打标签"><i class="fa fa-paper-plane"></i></a>');

                
            });

            // 导出按钮
            if (Admin::user()->cannot('application.column_recommends.export')) {
                $grid->disableExport();
            }

            // 批量操作
            $grid->tools(function ($tools) {
                $tools->batch(function ($batch) {
                    // 批量删除按钮
                    if (Admin::user()->cannot('application.column_recommends.batch_destroy')) {
                        $batch->disableDelete();
                    }
                });
            });

            $grid->column('id', 'ID')->sortable();
            $grid->column('area', '区域编号')->sortable();
            $grid->column('name', '名称')->sortable();
            $grid->column('title', '显示名称')->sortable();
            $grid->column('description', '描述')->sortable();
            $grid->column('column.name', '一级栏目')->sortable();

            $grid->columnRecommendDatas('推荐数据')->pluck('title')->implode('&nbsp;&nbsp;<br/>')->label();
            /**
             * 过滤处理
             */
            $grid->filter(function ($filter) {
                // // 禁用id查询框
                // $filter->disableIdFilter();
                $filter->like('name', '名称');

            });
        });
    }

    /**
     * 加载公共区域视图
     * @param Request $request [description]
     */
    public function addRecommendDatas(Request $request)
    {
        Admin::script('addPublicRecommendData();');

        // $sys_categories = new sys_categories();
        // $tag_groups     = $sys_categories->tagGroup(false);

        // $tag_content_type = addslashes(tag_content::$tag_content_type[$request->get('tag_content_type')]);

        // $viewData = array(
        //     'tag_groups'       => json_decode($tag_groups, true),
        //     'tag_content_id'   => $request->get('tag_content_id'),
        //     'tag_content_type' => $tag_content_type,
        // );
        $columnRecommendId = $request->input('column_recommend_id');

        $columnRecommend = $this->columnRecommendRepository->findWithoutFail($columnRecommendId);

        if (empty($columnRecommend)) {
            Flash::error(__('application.column_recommends.not_found'));

            return redirect(route('application.column_recommends.index'));
        }
        $datas                        = [];
        $data                         = Data::get(['title', 'id'])->toArray();
        $datas['datas']               = $data;
        $datas['column_recommend_id'] = $columnRecommendId;
        return view('application.column-recommend-datas.create', $datas);
    }

    public function queryList(Request $request)
    {

        // 搜索框的值
        $search_value = $request->input('search_value');
        // 收费类型
        $tag_group = $request->input('tag_group');

        $data         = array();
        $data['draw'] = $request->get('draw');
        $start        = $request->get('start') ?: 0;
        $length       = $request->get('length') ?: 10;
        $order        = $request->get('order');
        $columns      = $request->get('columns');
        $search       = $request->get('search');

        $model_tag = new tag();
        $where     = array();
        if (!empty($tag_group)) {
            $where[] = array('tag_group', '=', $tag_group);
        }
        if (!empty($search_value)) {
            $where[] = array('name', 'like', '%' . $search_value . '%');
        }

        if ($order) {
            $orderColumData = $columns[$order[0]['column']]['data'];
        }
        // 排序字段
        $ord = '';
        if (!empty($orderColumData)) {
            $ord = $orderColumData . ' ' . $order[0]['dir'];
        } else {
            $ord = 'id asc';
        }
        list($data['recordsTotal'], $data['recordsFiltered'], $data['data']) = $model_tag->tagList($where, $start, $length, $ord);
        return response()->json($data);
    }
    /**
     * datatable返回数据
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function getDataByModel(Request $request)
    {
        // 搜索框的值
        $search_value = $request->input('search_value');
        // 专题id
        $dataType = $request->input('data_type');
        $data     = Data::where(['id' => $dataType])->first();
        $relation = [];
        if ($data) {
            # code...
            switch ($data->name) {
                case 'column0':
                    $model = new Column();
                    break;
                case 'column1':
                    $model = new Subcolumn();
                    break;
                case 'vasset':
                    $model    = new Vasseti();
                    $relation = ['vcat', 'actors', 'directors', 'vareas', 'vlangs', 'vyears', 'vcattags'];
                    break;
                case 'aasset':
                    $model    = new Vasseti();
                    $relation = ['vcat', 'actors', 'directors', 'vareas', 'vlangs', 'vyears', 'vcattags'];
                    break;
                case 'iasset':
                    $model    = new Vasseti();
                    $relation = ['vcat', 'actors', 'directors', 'vareas', 'vlangs', 'vyears', 'vcattags'];
                    break;
                case 'column_fun':
                    $model = new ColumnFun();
                    break;
                default:
                    $model    = new Vasseti();
                    $relation = ['vcat', 'actors', 'directors', 'vareas', 'vlangs', 'vyears', 'vcattags'];
                    break;
            }
        } else {
            $model = new Vasseti();
        }

        $model = (new \ReflectionClass($model))->getName();

        $data         = [];
        $data['draw'] = $request->get('draw');
        $start        = $request->get('start') ?: 0;
        $length       = $request->get('length') ?: 10;
        $order        = $request->get('order');
        $columns      = $request->get('columns');
        $search       = $request->get('search');
        if ($order) {
            $orderColumData = $columns[$order[0]['column']]['data'];
        }

        // 排序字段
        $ord = '';
        if (!empty($orderColumData)) {
            $ord = $orderColumData . ' ' . $order[0]['dir'];
        } else {
            $ord = 'id asc';
        }
        $data['recordsTotal']    = $model::count();
        $data['recordsFiltered'] = $model::count();
        $data['data']            = $model::with($relation)
            ->skip($start)->take($length)
            ->orderByRaw($ord)
            ->get();
        return response()->json($data);
    }

    /**
     * 推荐数据包
     * @param  tag_contentRequest $request [description]
     * @return [type]                      [description]
     */
    public function recommendStore(Request $request)
    {
        // 获取传递过来是哪个栏目推荐
        $columnRecommendId = $request->input('column_recommend_id');
        if (empty($columnRecommendId)) {
            return response()->json(['content' => '推荐位ID不能为空', 'status' => false]);
        }
        // 获取数据类型
        $dataType = $request->input('data_type');
        if (empty($dataType)) {
            return response()->json(['content' => '数据类型ID不能为空', 'status' => false]);
        }
        // 获取所有传递来的数据ID
        $dataId = $request->input('data_id');
        if (!is_array($dataId)) {
            return response()->json(['content' => '数据为空,请选择数据', 'status' => false]);
        }

        $data = Data::where(['id' => $dataType])->first();
        if (empty($data)) {
            return response()->json(['content' => '无此数据类型', 'status' => false]);

        }
        $datas = [];

        $colRecDatas = [];
        switch ($data->name) {
        	case 'collist':
                DB::beginTransaction();
                try {
                    foreach ($dataId as $key => $value) {
                        // 去推荐数据表中看是否已有此数据
                        $columnRecommendData = ColumnRecommendData::where(['data_id' => $dataType, 'resource_data_id' => $value])->first();
                        if (empty($columnRecommendData)) {
                            $collist = Collist::where(['id' => $value])->first();
                            if ($collist) {
                                $datas['name']             = $collist->name;
                                $datas['title']            = $collist->title;
                                $datas['data_id']          = $dataType;
                                $datas['resource_data_id'] = $value;
                                $datas['order']            = 0;
                                $columnRecommendDataId     = DB::table('column_recommend_datas')->insertGetId($datas);
                            }
                        } else {
                            $columnRecommendDataId = $columnRecommendData->id;
                        }
                        $colRecDatas[$key]['column_recommend_id']      = $columnRecommendId;
                        $colRecDatas[$key]['column_recommend_data_id'] = $columnRecommendDataId;
                    }
                    DB::table('column_recommend_column_recommend_datas')->insert($colRecDatas);
                    DB::commit();
                    return response()->json(['content' => '添加成功！', 'status' => true]);
                } catch (Exception $e) {
                    DB::rollback();
                }
            break;
            case 'column0':
                DB::beginTransaction();
                try {
                    foreach ($dataId as $key => $value) {
                        // 去推荐数据表中看是否已有此数据
                        $columnRecommendData = ColumnRecommendData::where(['data_id' => $dataType, 'resource_data_id' => $value])->first();
                        if (empty($columnRecommendData)) {
                            $column = Column::where(['id' => $value])->first();
                            if ($column) {
                                $datas['name']             = $column->name;
                                $datas['title']            = $column->name;
                                $datas['data_id']          = $dataType;
                                $datas['resource_data_id'] = $value;
                                $datas['order']            = 0;
                                $columnRecommendDataId     = DB::table('column_recommend_datas')->insertGetId($datas);
                            }
                        } else {
                            $columnRecommendDataId = $columnRecommendData->id;
                        }
                        $colRecDatas[$key]['column_recommend_id']      = $columnRecommendId;
                        $colRecDatas[$key]['column_recommend_data_id'] = $columnRecommendDataId;
                    }
                    DB::table('column_recommend_column_recommend_datas')->insert($colRecDatas);
                    DB::commit();
                    return response()->json(['content' => '添加成功！', 'status' => true]);
                } catch (Exception $e) {
                    DB::rollback();
                }
                break;
            case 'column1':
                DB::beginTransaction();
                try {
                    foreach ($dataId as $key => $value) {
                        // 去推荐数据表中看是否已有此数据
                        $columnRecommendData = ColumnRecommendData::where(['data_id' => $dataType, 'resource_data_id' => $value])->first();
                        if (empty($columnRecommendData)) {
                            $subcolumn = Subcolumn::where(['id' => $value])->first();
                            if ($subcolumn) {

                                $datas['name']             = $subcolumn->name;
                                $datas['title']            = $subcolumn->name;
                                $datas['data_id']          = $dataType;
                                $datas['resource_data_id'] = $value;
                                $datas['order']            = 0;
                                $columnRecommendDataId     = DB::table('column_recommend_datas')->insertGetId($datas);
                            }
                        } else {
                            $columnRecommendDataId = $columnRecommendData->id;
                        }
                        $colRecDatas[$key]['column_recommend_id']      = $columnRecommendId;
                        $colRecDatas[$key]['column_recommend_data_id'] = $columnRecommendDataId;
                    }
                    DB::table('column_recommend_column_recommend_datas')->insert($colRecDatas);
                    DB::commit();
                    return response()->json(['content' => '添加成功！', 'status' => true]);
                } catch (Exception $e) {
                    DB::rollback();
                }
                break;
            case 'vasset':
                DB::beginTransaction();
                try {
                    foreach ($dataId as $key => $value) {
                        // 去推荐数据表中看是否已有此数据
                        $columnRecommendData = ColumnRecommendData::where(['data_id' => $dataType, 'resource_data_id' => $value])->first();
                        if (empty($columnRecommendData)) {
                            $vasseti = Vasseti::where(['id' => $value])->first();
                            if ($vasseti) {

                                $datas['name']             = $vasseti->name;
                                $datas['title']            = $vasseti->name;
                                $datas['data_id']          = $dataType;
                                $datas['resource_data_id'] = $value;
                                $datas['order']            = 0;
                                $columnRecommendDataId     = DB::table('column_recommend_datas')->insertGetId($datas);
                            }
                        } else {
                            $columnRecommendDataId = $columnRecommendData->id;
                        }
                        $colRecDatas[$key]['column_recommend_id']      = $columnRecommendId;
                        $colRecDatas[$key]['column_recommend_data_id'] = $columnRecommendDataId;
                    }
                    DB::table('column_recommend_column_recommend_datas')->insert($colRecDatas);
                    DB::commit();
                    return response()->json(['content' => '添加成功！', 'status' => true]);
                } catch (Exception $e) {
                    DB::rollback();
                }
                break;
            case 'aasset':
                DB::beginTransaction();
                try {
                    foreach ($dataId as $key => $value) {
                        // 去推荐数据表中看是否已有此数据
                        $columnRecommendData = ColumnRecommendData::where(['data_id' => $dataType, 'resource_data_id' => $value])->first();
                        if (empty($columnRecommendData)) {
                            $vasseti = Vasseti::where(['id' => $value])->first();
                            if ($vasseti) {

                                $datas['name']             = $vasseti->name;
                                $datas['title']            = $vasseti->name;
                                $datas['data_id']          = $dataType;
                                $datas['resource_data_id'] = $value;
                                $datas['order']            = 0;
                                $columnRecommendDataId     = DB::table('column_recommend_datas')->insertGetId($datas);
                            }
                        } else {
                            $columnRecommendDataId = $columnRecommendData->id;
                        }
                        $colRecDatas[$key]['column_recommend_id']      = $columnRecommendId;
                        $colRecDatas[$key]['column_recommend_data_id'] = $columnRecommendDataId;
                    }
                    DB::table('column_recommend_column_recommend_datas')->insert($colRecDatas);
                    DB::commit();
                    return response()->json(['content' => '添加成功！', 'status' => true]);
                } catch (Exception $e) {
                    DB::rollback();
                }
                break;
            case 'iasset':
                DB::beginTransaction();
                try {
                    foreach ($dataId as $key => $value) {
                        // 去推荐数据表中看是否已有此数据
                        $columnRecommendData = ColumnRecommendData::where(['data_id' => $dataType, 'resource_data_id' => $value])->first();
                        if (empty($columnRecommendData)) {
                            $vasseti = Vasseti::where(['id' => $value])->first();
                            if ($vasseti) {

                                $datas['name']             = $vasseti->name;
                                $datas['title']            = $vasseti->name;
                                $datas['data_id']          = $dataType;
                                $datas['resource_data_id'] = $value;
                                $columnRecommendDataId     = DB::table('column_recommend_datas')->insertGetId($datas);
                            }
                        } else {
                            $columnRecommendDataId = $columnRecommendData->id;
                        }
                        $colRecDatas[$key]['column_recommend_id']      = $columnRecommendId;
                        $colRecDatas[$key]['column_recommend_data_id'] = $columnRecommendDataId;
                    }
                    DB::table('column_recommend_column_recommend_datas')->insert($colRecDatas);
                    DB::commit();
                    return response()->json(['content' => '添加成功！', 'status' => true]);
                } catch (Exception $e) {
                    DB::rollback();
                }
                break;
            case 'column_fun':
                DB::beginTransaction();
                try {
                    foreach ($dataId as $key => $value) {
                        // 去推荐数据表中看是否已有此数据
                        $columnRecommendData = ColumnRecommendData::where(['data_id' => $dataType, 'resource_data_id' => $value])->first();
                        if (empty($columnRecommendData)) {
                            $vasseti = ColumnFun::where(['id' => $value])->first();
                            if ($vasseti) {

                                $datas['name']             = $vasseti->name;
                                $datas['title']            = $vasseti->name;
                                $datas['data_id']          = $dataType;
                                $datas['resource_data_id'] = $value;
                                $datas['order']            = 0;
                                $columnRecommendDataId     = DB::table('column_recommend_datas')->insertGetId($datas);
                            }
                        } else {
                            $columnRecommendDataId = $columnRecommendData->id;
                        }
                        $colRecDatas[$key]['column_recommend_id']      = $columnRecommendId;
                        $colRecDatas[$key]['column_recommend_data_id'] = $columnRecommendDataId;
                    }
                    DB::table('column_recommend_column_recommend_datas')->insert($colRecDatas);
                    DB::commit();
                    return response()->json(['content' => '添加成功！', 'status' => true]);
                } catch (Exception $e) {
                    DB::rollback();
                }
                break;
            default:
                break;
        }
    }
}
